package cn.tedu.csmall.order.service.impl;



import cn.tedu.csmall.commons.exception.CoolSharkServiceException;
import cn.tedu.csmall.commons.pojo.order.dto.OrderAddDTO;
import cn.tedu.csmall.commons.pojo.order.model.OrderTb;
import cn.tedu.csmall.commons.pojo.stock.dto.StockReduceCountDTO;
import cn.tedu.csmall.commons.restful.ResponseCode;
import cn.tedu.csmall.order.client.CartClient;
import cn.tedu.csmall.order.client.StockClient;
import cn.tedu.csmall.order.mapper.OrderMapper;
import cn.tedu.csmall.order.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    StockClient stockClient;

    @Autowired
    CartClient cartClient;


    @Override
    public void orderAdd(OrderAddDTO orderAddDTO) {
        //1.减少订单中的商品的库存(要调用stock模块)
        StockReduceCountDTO stockReduceCountDTO=new StockReduceCountDTO();
        stockReduceCountDTO.setCommodityCode(orderAddDTO.getCommodityCode());
        stockReduceCountDTO.setReduceCount(orderAddDTO.getCount());
        //        restTemplate.postForObject(
//                "http://stock/base/stock/reduce/count",
//                stockReduceCountDTO,
//                JsonResult.class);
        System.out.println(stockClient);
        stockClient.reduceCommodityCount(stockReduceCountDTO);
        System.out.println("调用stock删除库存成功");
        //2.删除订单中勾选的商品
        cartClient.deleteCartByUserIdAndCommodity(orderAddDTO.getUserId(),orderAddDTO.getCommodityCode());
        System.out.println("调用cart删除购物车成功");
        //3.新增订单
        OrderTb order = new OrderTb();
        BeanUtils.copyProperties(orderAddDTO, order);
        //执行mapper的新增方法
        int row = orderMapper.insertOrder(order);
        if (row == 0){
            throw new CoolSharkServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"操作数据库失败");
        }
        log.info("订单新增成功:{}", order);
    }
}
